import os
import re
import sys

from util import validate_activation_code

# 获取当前目录
current_dir = r"./sproto"


if not os.path.exists(current_dir):
    input("协议文件放在当前目录下的sproto文件夹")
    sys.exit()

gametype = "gametype.sproto"
keyCode = "594da6dc3079fc1115081d7dfb63154be41100e6efb34466b826c4033006a378"

 
if not validate_activation_code(keyCode):
    input("按任意键退出")
    sys.exit()

allTxt = ""
with open(os.path.join(current_dir,gametype) , "r",encoding="utf-8") as f:
    # 读取文件内容
    allTxt = allTxt+"\n" + f.read()

# 获取所有文件名
file_names = os.listdir(current_dir)


for file_name in file_names:
    if gametype == file_name:
        continue
    # 打开文件
    with open(os.path.join(current_dir,file_name) , "r",encoding="utf-8") as f:
        # 读取文件内容
        allTxt = allTxt+"\n" + f.read()

allTxt = re.sub(r"#", "//", allTxt)
tsType ={
    "integer":"number"
}
def replaceType(matched):
    txt = matched.group(0)
    if "//" in txt[0:10]:
        return txt
    
    isArr = False
    if "*" in txt:
       isArr = True
     
    txt = re.search(r"[a-zA-Z_0-9]*\d*$", txt).group(0)
    if txt in tsType:
        txt = tsType[txt]
    if isArr:
        txt =  txt + "[]"
    return ":" + txt

allTxt = re.sub(r"\d+\s*:\s*\**[a-zA-Z_0-9]*",  replaceType, allTxt)

def replaceRequest(matched):
    txt = matched.group(0)
    if "//" in txt[0:10]:
        return txt
    return "\n\trequest : {" 
allTxt = re.sub(r"/*\s*request\s*\{{1}",  replaceRequest, allTxt)

def replaceResponse(matched):
    txt = matched.group(0)
    if "//" in txt[0:10]:
        return txt
    return "\n\tresponse : {" 
allTxt = re.sub(r"/*\s*response\s*\{{1}",  replaceResponse, allTxt)

typeData = {}
def replaceData(matched):
    txt = matched.group(0)
    if "//" in txt[0:10]:
        return txt
    txt = txt.replace(".","")
    if "package {" in txt:
        txt = "spbPackage {"
    typeData[re.search(r"[a-zA-Z_0-9]+\d*", txt).group(0)] = 1
    return  txt
allTxt = re.sub(r".*\..*\n*\{{1}",  replaceData, allTxt)

def replaceProto(matched):
    global protoTs
    txt = matched.group(0)
    if "//" in txt[0:10] :
        return txt
    txt = re.search(r"[a-zA-Z_0-9]+\d*", txt).group(0)
    if txt in typeData :
       return "export class " + txt + " {" 
    else:
        return "export class " + txt + " {  \n    static type = \"" + str(txt) + "\"" 
allTxt = re.sub(r"[a-zA-Z_0-9]+\s*[0-9]*\s*\n*\{{1}",  replaceProto, allTxt)


allTxt = allTxt.replace("\n","\n    ")
# def replace(matched):
#     print(matched)
#     return "interface" + matched
# allTxt = re.sub(r"^.*?\{", replace, allTxt)
allTxt = " /**注意！！！！！ 改文件由脚本生成不要改动*/\n\n\n\nexport namespace Spb{\n" + allTxt + "\n};\nwindow['Spb'] = Spb"
with open("SprotoType.ts", "w",encoding="utf-8") as file:
  file.write(allTxt)

input("转换完成，按任意键退出")